// 此模块，用于管理路由数组 权限信息 (可以控制访问权限)
import { constantRoutes, asyncRouter } from '@/router'

const state = {
  routers: constantRoutes
}
const mutations = {
  // 根据后台返回的权限，动态的新增动态路由
  setRouter(state, otherRouter) {
    state.routers = [
      ...constantRoutes,
      ...otherRouter
    ]
  }

}
const actions = {
  filterRoutes(context, menus) {
    const menuMap = new Map()
    for (let i = 0; i < menus.length; i++) {
      menuMap.set(menus[i].authority, menus[i])
    }
    let otherRouter = []
    const filterRoute = (asyncRouter, menus) => {
      for (let i = 0; i < asyncRouter.length; i++) {
        if (menus.get(asyncRouter[i].name)) {
          if (asyncRouter[i].name === menus.get(asyncRouter[i].name).authority) {
            asyncRouter[i].meta.title = menus.get(asyncRouter[i].name).authorityName
          }
        }
        if (asyncRouter[i].children) {
          filterRoute(asyncRouter[i].children, menus)
          if (asyncRouter[i].children.length) {
            continue
          }
        }
        if (!menus.get(asyncRouter[i].name)) {
          asyncRouter.splice(i, 1)
          i--
        }
      }
    }
    filterRoute(asyncRouter, menuMap)
    otherRouter = asyncRouter
    context.commit('setRouter', otherRouter)
    return otherRouter
  }
}
const getters = {}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}
